﻿using System;
using System.IO;
using System.Windows.Input;
using VisualWip.Core;
using VisualWip.Core.Columns;
using VisualWip.Core.Interfaces;
using VisualWip.Util;
using System.Linq;

namespace VisualWip.PresentationModel.Image
{
    public class ImageColumnSettingsViewModel : SettingsViewModelBase<ImageColumn>
    {
        private readonly IPathSelector _filePathSelector;
        private ICommand _selectFileCommand;

        public ImageColumnSettingsViewModel(Application application, ImageColumn column, IColumnTypeProvider columnTypeProvider,
                                            IPathSelector filePathSelector)
            : base(application, column, columnTypeProvider)
        {
            _filePathSelector = filePathSelector;
        }

        public override string SettingsWindowName
        {
            get { return "Image column settings"; }
        }

        public string ImagePath
        {
            get { return Column.ImagePath; }
            set
            {
                if (value != Column.ImagePath)
                {
                    Column.ImagePath = value;
                    SetColumnName(Column.ImagePath);
                    OnPropertyChanged(this, () => ImagePath);
                }
            }
        }

        private void SetColumnName(string imagePath)
        {
            System.Uri uri;
            if (String.IsNullOrWhiteSpace(ColumnName) && System.Uri.TryCreate(imagePath, UriKind.RelativeOrAbsolute, out uri))
            {
                if (uri.IsFile)
                {
                    ColumnName = Path.GetFileName(imagePath);
                    return;
                }
                if (string.IsNullOrWhiteSpace(uri.Query))
                {
                    ColumnName = uri.Segments.LastOrDefault();
                    return;
                }

                ColumnName = uri.Query.TrimStart('?');
            }
        }

        public ICommand SelectFileCommand
        {
            get
            {
                if (_selectFileCommand == null)
                {
                    _selectFileCommand = new RelayCommand(param => SelectFile());
                }
                return _selectFileCommand;
            }
        }

        private void SelectFile()
        {
            _filePathSelector.Filter = "Image files|*.jpg;*.jpeg,*.gif;*.png;*.bmp|All files|*.*";
            _filePathSelector.DefaultExtension = "";
            _filePathSelector.DefaultFileName = "";
            PathSelectorResult selectedFile = _filePathSelector.OpenSelector();

            if (selectedFile.IsSelectionMade)
                ImagePath = selectedFile.Path.Path;
        }
    }
}